package com.fenfen.novel;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import com.fenfen.novel.fragment.NovelListFragment;
import com.fenfen.novel.model.Category;
import com.fenfen.novel.utils.CommonUtil;

import org.parceler.Parcels;

public class NovelListActivity extends BaseActivity {

  private static String Tag = NovelListActivity.class.getSimpleName();

  public static String EXTRA_CATEGORY = "category";

  private Category category;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_novel_list);

    initIntentData();

    initToolbar();
    replaceFragment();
  }

  private void initToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
      setSupportActionBar(toolbar);
      getSupportActionBar().setTitle(category.getName());
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        super.onBackPressed();
        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  private void replaceFragment() {
    Bundle bundle = new Bundle();
    bundle.putByte(NovelListFragment.EXTRA_DATA_TYPE, CommonUtil.NovelListType.TYPE_NOVEL_CATEGORY);
    bundle.putInt(NovelListFragment.EXTRA_CATEGORY_ID, category.getId());
    NovelListFragment fragment = NovelListFragment.newInstance(bundle);

    FragmentManager fm = getSupportFragmentManager();
    fm.beginTransaction().replace(R.id.container, fragment).commit();
  }

  private void initIntentData() {
    category = Parcels.unwrap(getIntent().getParcelableExtra(EXTRA_CATEGORY));
  }
}
